<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2017/9/21
 * Time: 17:22
 */

namespace Home\Service;


use Admin\Enums\AuthorType;
use Home\Controller\UploadController;
use Think\Model;
use Think\Page;

class SheetService extends Model
{
    /**
     * 获取曲谱排行
     * @param $page
     * @param $limit
     * @return mixed
     */
    public function sheetRank($map, $page, $limit, $order, &$count = 0)
    {
        $count = M('Sheet')->where($map)->count();
        if (!$count) {
            return [];
        }
        $list = M('Sheet')->field('id, name, singer, song_name, comment_count, fav_count, creator, author_type')->where($map)->order($order)->page($page, $limit)->select();

        $sheetIds = array_column($list, 'id');
        //获取曲谱第一张图片链接
        $imgService = new ImageSheetService();
        $imgSheetMap = $imgService->sheetImg($sheetIds);
        //获取收藏该曲谱的用户列表
        $sheetUserMap = $this->favSheetList($sheetIds);

        //获取用户喜欢的曲谱列表
        $user = session('user');
        if (!empty($user)) {
            $favService = new SheetFavoriteService();
            $userId = $user['uid'];
            $sheetFavMap = $favService->getUserFavList($userId);
        }

        foreach ($list as $key => $val) {
            /*if($val['author_type'] == AuthorType::$ADMIN) {
                $userInfo = M('Member')->where(array('uid'=>$val['creator']))->find();
                $list[$key]['creator_info']['nickname'] = $userInfo['nickname'];
            } else {*/
            $userInfo = M('User')->where(array('id'=>$val['creator']))->find();
            $list[$key]['creator_info']['nickname'] = $userInfo['nickname'];
            $list[$key]['creator_info']['avatar_url'] = $userInfo['avatar_url'];

            $list[$key]['img_url'] = str_replace("'", "\'", $imgSheetMap[$val['id']][0]['url']);
            $list[$key]['img_count'] = count($imgSheetMap[$val['id']]);
            $list[$key]['fav_user'] = $sheetUserMap[$val['id']];
            $list[$key]['fav_status'] = isset($sheetFavMap[$val['id']]) ? 1 : 0;
        }

        return $list;
    }

    /**
     * 获取曲谱排行榜列表
     * @param $map
     * @param $page
     * @param $limit
     * @param $order
     * @param $count
     * @return array
     */
    public function topRank($map, $page, $limit, $order, &$count)
    {
        $count = count(M('Sheet')->field('id, name, singer, song_name, comment_count, fav_count, creator, author_type')->where($map)->order($order)->limit(100)->select());
        $subQuery = M('Sheet')->field('id, name, singer, song_name, comment_count, fav_count, creator, author_type')->where($map)->order($order)->limit(100)->buildSql();
        $list = M('Sheet')->table($subQuery. ' a')
            ->field('a.*')
            ->page($page, $limit)->select();
        if (!$list) {
            return [];
        }
        $sheetIds = array_column($list, 'id');
        //获取曲谱第一张图片链接
        $imgService = new ImageSheetService();
        $imgSheetMap = $imgService->sheetImg($sheetIds);
        //获取收藏该曲谱的用户列表
        $sheetUserMap = $this->favSheetList($sheetIds);

        //获取用户喜欢的曲谱列表
        $user = session('user');
        if (!empty($user)) {
            $favService = new SheetFavoriteService();
            $userId = $user['uid'];
            $sheetFavMap = $favService->getUserFavList($userId);
        }

        foreach ($list as $key => $val) {
            /*if($val['author_type'] == AuthorType::$ADMIN) {
                $userInfo = M('Member')->where(array('uid'=>$val['creator']))->find();
                $list[$key]['creator_info']['nickname'] = $userInfo['nickname'];
            } else {*/
            $userInfo = M('User')->where(array('id'=>$val['creator']))->find();
            $list[$key]['creator_info']['nickname'] = $userInfo['nickname'];
            $list[$key]['creator_info']['avatar_url'] = $userInfo['avatar_url'];

            $list[$key]['img_url'] = str_replace("'", "\'", $imgSheetMap[$val['id']][0]['url']);
            $list[$key]['img_count'] = count($imgSheetMap[$val['id']]);
            $list[$key]['fav_user'] = $sheetUserMap[$val['id']];
            $list[$key]['fav_status'] = isset($sheetFavMap[$val['id']]) ? 1 : 0;
        }

        return $list;
    }

    /**
     * 获取曲谱列表详情
     * @param $sheetList
     * @return mixed
     */
    public function getSheetInfo($sheetList)
    {
        $sheetIds = array_column($sheetList, 'sheet_id');
        if (empty($sheetIds)) {
            $sheetIds = array_column($sheetList, 'id');
        }
        //获取曲谱第一张图片链接
        $imgService = new ImageSheetService();
        $imgSheetMap = $imgService->sheetImg($sheetIds);

        //获取用户收藏状态
        $user = session('user');
        if (!empty($user)) {
            $favService = new SheetFavoriteService();
            $userId = $user['uid'];
            $sheetFavMap = $favService->getUserFavList($userId);
        }

        foreach ($sheetList as $key => $val) {
           /* if($val['author_type'] == AuthorType::$ADMIN) {
                $userInfo = M('Member')->where(array('uid'=>$val['creator']))->find();
                $sheetList[$key]['creator_info']['nickname'] = $userInfo['nickname'];
            } else {*/
            $userInfo = M('User')->where(array('id'=>$val['creator']))->find();
            $sheetList[$key]['creator_info']['nickname'] = $userInfo['nickname'];
            $sheetList[$key]['creator_info']['avatar_url'] = $userInfo['avatar_url'];

            $sheetList[$key]['img_url'] = $val['sheet_id'] ? str_replace("'", "\'", $imgSheetMap[$val['sheet_id']][0]['url']) : str_replace("'", "\'", $imgSheetMap[$val['id']][0]['url']);
            $sheetList[$key]['img_count'] = $val['sheet_id'] ? count($imgSheetMap[$val['sheet_id']]) : count($imgSheetMap[$val['id']]);
            $sheetList[$key]['fav_status'] = isset($sheetFavMap[$val['id']]) ? 1 : 0;
        }

        return $sheetList;
    }
    /**
     * 获取收藏曲谱的用户信息
     * @param $sheetIds
     * @return mixed
     */
    public function favSheetList($sheetIds)
    {
        $map = array(
            'sheet_id' => array('in', $sheetIds),
            'is_delete' => 0
        );
        //todo::解决获取数量过大的问题
        //step-1 获取收藏曲谱的用户列表
        $res = M('ScoreSheet')->where($map)->field('sheet_id, creator')->order('rand()')->select();

        $res = a_array_unique($res); //整理收藏至多个谱单的用户

        $userList = array_column($res, 'creator');
        //step-2 获取用户信息
        $userModel = new UserService();
        $userMap = $userModel->userinfoByIds($userList);
        foreach ($res as $key => $val) {
            $val['nickname'] = $userMap[$val['creator']]['nickname'];
            $val['avatar_url'] = $userMap[$val['creator']]['avatar_url'];
            $sheetUserMap[$val['sheet_id']][] = $val;
        }

        /*$list = M('User')->alias('u')->field('sc.creator, ss.sheet_id, u.nickname, u.avatar_url')
            ->join('score sc ON sc.creator = u.id')
            ->join('score_sheet ss ON sc.id = ss.score_id')
            ->where($map)->select();

        $list = a_array_unique($list);

        foreach ($list as $key => $val) {
            $sheetUserMap[$val['sheet_id']][] = $val;
        }*/

        return $sheetUserMap;
    }


    /**
     * 新增曲谱
     */
    public function addSheet($param){
        //step-1: 验证参数
        $Model = D('Sheet');
        $data = $Model->create($param);
        if($data){
            //step-2: 设置默认参数
            $param = $this->fillParam($param);

            //step-3: 保存谱单
            $id = $Model->add($param);

            //step-4:将本地图片上传阿里云
            $ossController = new UploadController();
            $imageIds = $ossController->uploadSheet($param);

            //step-5: 保存曲谱和图片的关系
            $imageSheetService = new ImageSheetService();
            $imageSheetService->saveRelation($imageIds, $id, $param['creator']);

            //step-6: 保存标签
            $tags = explode("," ,$param['tags']);
            $tagService = new TagService();
            foreach ($tags as $key=>$name) {
                $tag['name'] = $name;
                $tag_id = $tagService->save($tag, $param['creator']);
                $tag['id']  = $tag_id;
                $tags[$key] = $tag;
            }

            //step-7: 保存标签和曲谱的关系
            $tag_ids = array_column($tags, "id");
            $tagSheetService = new TagSheetService();
            $tagSheetService->save($tag_ids, $id, $param['creator']);

            return $id;
        } else {
            E($Model->getError());
        }
    }


    /**
     * 填充参数
     * @param unknown $param
     */
    private function fillParam($param)
    {
        $param['author_type'] = 20;
        $param['status'] = 0;
        return $param;
    }
}